<template>
  <div class="tinymce-container" :style="{ width: containerWidth }">
    <uploadBtn @uploadImages="handleDone"></uploadBtn>
    <textarea :id="tinymceId" ref="elRef">hello world</textarea>
  </div>
</template>
<script>
  import tinymce from 'tinymce/tinymce'
  import 'tinymce/themes/silver'
  import 'tinymce/icons/default/icons'
  import 'tinymce/plugins/advlist'
  import 'tinymce/plugins/anchor'
  import 'tinymce/plugins/autolink'
  import 'tinymce/plugins/autosave'
  import 'tinymce/plugins/code'
  import 'tinymce/plugins/codesample'
  import 'tinymce/plugins/directionality'
  import 'tinymce/plugins/fullscreen'
  import 'tinymce/plugins/hr'
  import 'tinymce/plugins/insertdatetime'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/media'
  import 'tinymce/plugins/nonbreaking'
  import 'tinymce/plugins/noneditable'
  import 'tinymce/plugins/pagebreak'
  import 'tinymce/plugins/paste'
  import 'tinymce/plugins/preview'
  import 'tinymce/plugins/print'
  import 'tinymce/plugins/save'
  import 'tinymce/plugins/searchreplace'
  import 'tinymce/plugins/tabfocus'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/template'
  import 'tinymce/plugins/textpattern'
  import 'tinymce/plugins/visualblocks'
  import 'tinymce/plugins/visualchars'
  import 'tinymce/plugins/wordcount'

  import { toolbar, plugins } from './tinymce'
  import {
    defineComponent,
    ref,
    computed,
    unref,
    watch,
    nextTick,
    onBeforeUnmount,
    onDeactivated,
    emit,
  } from 'vue'
  import { isNumber } from '@/utils/validate'
  import { onMountedOrActivated } from '@/hooks/core/onMountedOrActivated'
  import { bindHandlers } from './helper'
  import uploadBtn from './EditorUploadBtn'
  const tinymceProps = {
    options: {
      type: Object,
      default: {},
    },
    value: {
      type: String,
    },
    toolbar: {
      type: Array,
      default: toolbar,
    },
    plugins: {
      type: Array,
      default: plugins,
    },
    modelValue: {
      type: String,
    },
    height: {
      type: [Number, String],
      required: false,
      default: 400,
    },
    showImageUpload: {
      type: Boolean,
      default: true,
    },
  }
  export default defineComponent({
    name: 'Tinymce',
    inheritAttrs: false,
    props: tinymceProps,
    components: { uploadBtn },
    emits: ['change', 'update:modelValue', 'inited', 'init-error'],
    setup(props, { emit, attrs }) {
      const editorRef = ref(null)
      const fullscreen = ref(false)
      const tinymceId = ref('tiny-vue')
      const elRef = ref(null)

      const tinymceContent = computed(() => props.modelValue)
      const containerWidth = computed(() => {
        const width = props.width
        if (isNumber()) {
          return `${width}px`
        }
        return width
      })

      const langeName = computed(() => {
        // 国际化预留接口
        return 'zh_CN'
      })
      const skinName = computed(() => {
        // 换肤预留接口
        return 'oxide'
      })

      const initOptions = computed(() => {
        // 一定要保证height有值 否者看不见输入框
        const { height, options, toolbar, plugins } = props
        const publicPath = '/'
        return {
          selector: `#${unref(tinymceId)}`,
          height,
          toolbar,
          menubar: 'file edit insert view format table',
          plugins,
          language_url:
            publicPath + 'resource/tinymce/langs/' + langeName.value + '.js',
          language: langeName.value,
          branding: false,
          default_link_target: '_blank',
          link_title: false,
          object_resizing: false,
          auto_focus: true,
          skin: skinName.value,
          skin_url: publicPath + 'resource/tinymce/skins/ui/' + skinName.value,
          content_css:
            publicPath +
            'resource/tinymce/skins/ui/' +
            skinName.value +
            '/content.min.css',
          // images_upload_url: 'http://tinymce.ax-z.cn/demo/upimg.php',
          // images_upload_base_path: '/demo',
          // images_upload_handler: function (blobInfo, successcb, failcb) {
          //
          //   console.log(blobInfo)
          // },
          ...options,
          setup: (editor) => {
            editorRef.value = editor
            editor.on('init', (e) => initSetup(e))
          },
        }
      })

      const disabled = computed(() => {
        const { options } = props
        const getdDisabled = options && Reflect.get(options, 'readonly')
        const editor = unref(editorRef)
        if (editor) {
          editor.mode.set(getdDisabled ? 'readonly' : 'design')
        }
        return getdDisabled ?? false
      })

      watch(
        () => attrs.disabled,
        () => {
          const editor = unref(editorRef)
          if (!editor) {
            return
          }
          editor.mode.set(attrs.disabled ? 'readonly' : 'design')
        }
      )

      onMountedOrActivated(() => {
        if (!initOptions.value.inline) {
          tinymceId.value = 'tiny-vue'
        }

        nextTick(() => {
          setTimeout(() => {
            initEditor()
          }, 30)
        })
      })
      onBeforeUnmount(() => {
        destory()
      })

      onDeactivated(() => {
        destory()
      })

      function destory() {
        if (tinymce !== null) {
          tinymce.remove(unref(initOptions).selector)
        }
      }

      function initEditor() {
        const el = unref(elRef)
        if (el) {
          el.style.visibility = ''
        }

        tinymce
          .init(unref(initOptions))
          .then((editor) => {
            emit('inited', editor)
          })
          .catch((err) => {
            emit('init-error', err)
          })
      }

      function initSetup(e) {
        const editor = unref(editorRef)
        if (!editor) {
          return
        }
        const value = props.modelValue || ''

        editor.setContent(value)
        bindModelHandlers(editor)
        bindHandlers(e, attrs, unref(editorRef))
      }

      function setValue(editor, val, prevVal) {
        if (
          editor &&
          typeof val === 'string' &&
          val !== prevVal &&
          val !== editor.getContent({ format: attrs.outputFormat })
        ) {
          editor.setContent(val)
        }
      }

      // Inserts content at caret position.
      function setInsertValue(editor, val) {
        editor.insertContent(val)
      }
      function bindModelHandlers(editor) {
        const modelEvents = attrs.modelEvents ? attrs.modelEvents : null
        const normalizedEvents = Array.isArray(modelEvents)
          ? modelEvents.join('')
          : modelEvents

        watch(
          () => props.modelValue,
          (val, prevVal) => {
            setValue(editor, val, prevVal)
          }
        )

        watch(
          () => props.value,
          (val, prevVal) => {
            setValue(editor, val, prevVal)
          },
          {
            immediate: true,
          }
        )
        editor.on(
          normalizedEvents ? normalizedEvents : 'change keyup undo redo',
          () => {
            const content = editor.getContent({ format: attrs.outputFormat })
            emit('update:modelValue', content)
            emit('change', content)
          }
        )

        editor.on('FullscreenStateChanged', (e) => {
          fullscreen.value = e.state
        })
      }

      // function handleImageUploading(name) {}

      function handleDone(urls = []) {
        console.log('urls =' + JSON.stringify(urls))

        const editor = unref(editorRef)
        if (!editor) {
          return
        }
        urls.forEach(({ url }) => {
          const val = `<img src="${url}"/>`
          setInsertValue(editor, val)
        })

        // setValue(editor, val)
        // editor.insertContent(val)

        // editor.setContent(val)
        // const content = editor?.getContent() ?? ''
        // eslint-disable-next-line max-len
        // const val = content?.replace(getUploadingImgName(name), `<img src="${url}"/>`) ?? ''
        // setValue(editor, val)
      }

      // function getUploadingImgName(name) {
      //   return `[uploading:${name}]`
      // }
      return {
        tinymceId,
        disabled,
        initOptions,
        containerWidth,
        tinymceContent,
        handleDone,
      }
    },
  })
</script>
<style lang="scss">
  .tinymce-container {
    position: relative;
    line-height: normal;

    textarea {
      z-index: -1;
      visibility: hidden;
    }
  }
</style>
